﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.ISerivces;
using DWF.Studio.PlatformApi;
using DWF.Studio.Project;
using DWF.Studio.Share.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace DWF.Studio.Services
{
    internal class ProjectDeployService : IProjectDeployService
    {
        private IRobotService _robotService = null;

        private ProjectManager _projectManager = null;

        public ProjectDeployService(IRobotService robotService)
        {
            _robotService = robotService;
            _projectManager = ProjectManager.Instance;
        }
        /// <summary>
        /// 发布本地
        /// </summary>
        /// <param name="targetPath"></param>
        /// <param name="version"></param>
        /// <param name="description"></param>
        /// <param name="containLibs"></param>
        /// <param name="containPackages"></param>
        /// <param name="allowParallel"></param>
        /// <param name="requireAdmin"></param>
        public void PublishToLocal(string targetPath, string version, string description, bool isCustomContent, bool containPackages, bool allowParallel, bool requireAdmin, List<ProjectTreeView> projectFolders = null)
        {
            var procname = String.Format("{0}({1})", this._projectManager.CurrentProject.Name, version);

            if (!String.IsNullOrWhiteSpace(targetPath) && FileHelper.CheckFolderExisting(targetPath))
            {
                var files = Directory.GetFiles(targetPath, "*.process", SearchOption.TopDirectoryOnly);
                var tempname = procname;

                if (files != null)
                {
                    var filenames = files.Select(item => System.IO.Path.GetFileNameWithoutExtension(item));
                    var isContinue = true;
                    int num = 0;

                    while (isContinue)
                    {
                        isContinue = filenames.Any(item => item == procname);
                        if (isContinue)
                        {
                            num++;
                            procname = String.Format("{0}_{1}", tempname, num.ToString());
                        }
                    }
                }

                var temporary = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, StaticResource.TemporaryFolder);
                var proc = _projectManager.BuidProject(temporary, version, description, procname, isCustomContent, containPackages, allowParallel, requireAdmin, projectFolders);

                FileHelper.CopyFileToFolder(proc, targetPath);
                FileHelper.DeleteFile(proc);

                _projectManager.ModifyProjectVersion(version);
            }
        }
        /// <summary>
        /// 发布机器人
        /// </summary>
        /// <param name="targetPath"></param>
        /// <param name="version"></param>
        /// <param name="description"></param>
        /// <param name="containLibs"></param>
        /// <param name="containPackages"></param>
        /// <param name="allowParallel"></param>
        /// <param name="requireAdmin"></param>
        /// <returns></returns>
        public async Task PublishToRobotAsync(string targetPath, string version, string description, bool isCustomContent, bool containPackages, bool allowParallel, bool requireAdmin, List<ProjectTreeView> projectFolders = null)
        {
            var temporary = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, StaticResource.TemporaryFolder);
            var proc = _projectManager.BuidProject(temporary, version, description, Guid.NewGuid().ToString("N"), isCustomContent, containPackages, allowParallel, requireAdmin, projectFolders);

            FileHelper.CopyFileToFolder(proc, targetPath);
            FileHelper.DeleteFile(proc);

            _projectManager.ModifyProjectVersion(version);

            await Task.Run(() => _robotService.NoticePublishProcess(Path.Combine(targetPath, Path.GetFileName(proc))));
        }

        /// <summary>
        /// 发布exe可执行程序到本地
        /// </summary>
        /// <param name="targetPath"></param>
        /// <param name="version"></param>
        /// <param name="description"></param>
        /// <param name="containLibs"></param>
        /// <param name="containPackages"></param>
        /// <param name="allowParallel"></param>
        /// <param name="requireAdmin"></param>
        public void PublishToApplication(string targetPath, string version, string description, bool isCustomContent, bool containPackages, bool allowParallel, bool requireAdmin, List<ProjectTreeView> projectFolders = null)
        {
            var procname = String.Format("{0}({1})", this._projectManager.CurrentProject.Name, version).Replace(" ", "");

            if (!String.IsNullOrWhiteSpace(targetPath) && FileHelper.CheckFolderExisting(targetPath))
            {
                var files = Directory.GetFiles(targetPath, "*.exe", SearchOption.TopDirectoryOnly);
                var tempname = procname;

                if (files != null)
                {
                    var filenames = files.Select(item => System.IO.Path.GetFileNameWithoutExtension(item));
                    var isContinue = true;
                    int num = 0;

                    while (isContinue)
                    {
                        isContinue = filenames.Any(item => item == procname);
                        if (isContinue)
                        {
                            num++;
                            procname = String.Format("{0}_{1}", tempname, num.ToString());
                        }
                    }
                }

                var temporary = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, StaticResource.TemporaryFolder);
                var proc = _projectManager.BuidProject(temporary, version, description, procname, isCustomContent, containPackages, allowParallel, requireAdmin, projectFolders, true);

                FileHelper.CopyFileToFolder(proc, targetPath);
                FileHelper.DeleteFile(proc);

                _projectManager.ModifyProjectVersion(version);
            }
        }
    }
}
